<template>
  <div>
    <el-dialog
      title="审核任务"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="90%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      :destroy-on-close="true"
      @open="handleOpen"
      @close="handleClose"
    >
      <div class="dialog-content">
        <el-button
          type="primary"
          plain
          class="modify-btn"
          size="small"
          @click="handleModify"
          >修改填报内容</el-button
        >

        <FillForm
          ref="FillForm"
          :key="updateForm"
          v-loading="loading"
          :formName="formName"
          :headerForm="headerForm"
          :formFieldConfig="templateConfig"
          :formData="formData"
          :formWorkOrder="formWorkOrder"
          :renderingMode="renderingMode"
          :disabled="true"
        ></FillForm>

        <el-divider v-if="!!participants.length"></el-divider>

        <el-row v-for="(row, i) in participants" :key="i">
          <el-col :span="3"> 参与人：{{ row.participantName }} </el-col>
          <el-col :span="12">
            非生产小时数：
            {{ row.participationDuration }}
            小时
          </el-col>
        </el-row>

        <el-divider></el-divider>

        <el-form
          :model="examineFrom"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
        >
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="审核结果" prop="result">
                <el-radio-group v-model="examineFrom.result">
                  <el-radio label="1">同意</el-radio>
                  <el-radio label="2">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="审核意见" prop="opinion">
                <el-input
                  v-model="examineFrom.opinion"
                  type="textarea"
                  :rows="4"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button :loading="saveLoading" type="primary" @click="handleSubmit"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="修改填报内容"
      :visible.sync="modifyDialogVisible"
      :modal="true"
      :appendToBody="true"
      width="90%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      :destroy-on-close="true"
      @open="handleModifyOpen"
      @close="handleModifyClose"
    >
      <FillForm
        ref="ModifyFillForm"
        :key="key"
        :formName="formName"
        :headerForm="modifyHeaderForm"
        :formFieldConfig="templateConfig"
        :formData="formData"
        :formWorkOrder="formWorkOrder"
        :renderingMode="renderingMode"
      ></FillForm>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogVisible = false">取消</el-button>
        <el-button
          :loading="modifyLoading"
          type="primary"
          @click="handleSubmitModify"
          >提交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import FillForm from "../fillForm";
import {
  getTaskDetail,
  getTaskContent,
  saveTaskContent,
  saveTask,
  getTaskTemplateByTaskId,
} from "@/api/taskMgmt/center";
import { mapGetters } from "vuex";
export default {
  components: { FillForm },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      taskDetail: null,
      templateConfig: null,
      formData: null,
      formWorkOrder: null,
      execTime: null,
      // 参与人
      participants: [],
      examineFrom: {
        result: null,
        opinion: null,
      },
      rules: {
        result: [
          { required: true, message: "请选择审核结果", trigger: "change" },
        ],
        opinion: [
          {
            max: 200,
            message: "审核意见字段长度最大为200个字符",
            trigger: "change",
          },
        ],
      },
      loading: false,
      saveLoading: false,
      modifyDialogVisible: false,
      modifyLoading: false,
      key: 1,
      updateForm: 1,
    };
  },
  computed: {
    ...mapGetters(["realname"]),
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    formName() {
      return this.row?.taskName || "";
    },
    renderingMode() {
      return this.row?.renderingMode || "1";
    },
    headerForm() {
      const data = this.taskDetail;
      // 同时判断data和execTime都不为空才返回headerForm的内容值，目的时为了避免重复计算
      if (!data || !this.execTime) {
        return {
          ownedFactory: null,
          ownedFactoryName: null,
          ownedWorkshopId: null,
          ownedWorkshopName: null,
          ownedProductionLineId: null,
          ownedProductionLineName: null,
          groupId: null,
          groupName: null,
          className: null,
          executorName: null,
          auditorName: null,
          date: null,
          actualExecuteStartTime: null,
          actualExecuteEndTime: null,
        };
      }
      return {
        ownedFactory: data.ownedFactory,
        ownedFactoryName: data.ownedFactoryName,
        ownedWorkshopId: data.ownedWorkshopId,
        ownedWorkshopName: data.ownedWorkshopName,
        ownedProductionLineId: data.ownedProductionLineId,
        ownedProductionLineName: data.ownedProductionLineName,
        groupId: data.groupId,
        groupName: data.groupName,
        className: data.className,
        executorName: this.getOperatorLabel(data),
        auditorName: data.auditorName,
        date: this.execTime,
        actualExecuteStartTime: data.actualExecuteStartTime,
        actualExecuteEndTime: data.actualExecuteEndTime,
      };
    },
    modifyHeaderForm() {
      // 修改弹窗不显示时，不赋值
      if (!this.modifyDialogVisible) {
        return {};
      }
      const headerForm = {
        ...this.headerForm,
        executorName: this.realname,
        date: this.parseTime(new Date(), "{y}-{m}-{d}"),
      };
      return headerForm;
    },
  },
  methods: {
    handleClose() {
      this.templateConfig = {};
      this.formData = null;
      this.formWorkOrder = null;
      this.participants = [];
      this.$refs.ruleForm.resetFields();
    },
    handleOpen() {
      // 查询任务详情
      this.getTaskDetail();
      // 获取任务模板的单据设计 以及 表单填报内容
      this.getTemplateAndContent();
    },
    // 获取任务详情
    getTaskDetail() {
      if (!this.row?.id) {
        return;
      }
      getTaskDetail(this.row.id)
        .then((res) => {
          this.taskDetail = res?.data || null;
        })
        .catch(() => {
          this.taskDetail = null;
        });
    },
    // 获取模板及填报内容
    getTemplateAndContent() {
      if (!this.row?.id) {
        return;
      }
      this.loading = true;
      Promise.all([
        getTaskTemplateByTaskId(this.row.id),
        getTaskContent({ missionCenterId: this.row.id }),
      ])
        .then(([res1, res2]) => {
          // 任务模板的单据设计
          if (res1?.data && res1?.data != "null") {
            this.templateConfig = JSON.parse(res1.data);
          } else {
            this.templateConfig = null;
          }
          // 填报内容
          this.participants = res2?.data?.taskParticipantList || [];
          this.formData = res2?.data?.taskContentDtoList || [];
          this.execTime =
            res2?.data?.execTime || this.parseTime(new Date(), "{y}-{m}-{d}");
          this.formWorkOrder = {
            workOrderNo: res2?.data?.workOrderNo,
            workOrderName: res2?.data?.workOrderName,
          };
        })
        .catch(() => {
          this.templateConfig = null;
          this.formData = null;
          this.formWorkOrder = null;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取填报内容
    getFormContent() {
      if (!this.row?.id) {
        return;
      }
      const param = {
        missionCenterId: this.row.id,
      };
      getTaskContent(param).then((res) => {
        this.participants = res?.data?.taskParticipantList || [];
        this.formData = res?.data?.taskContentDtoList || [];
        this.execTime =
          res?.data?.execTime || this.parseTime(new Date(), "{y}-{m}-{d}");
        this.formWorkOrder = {
          workOrderNo: res?.data?.workOrderNo,
          workOrderName: res?.data?.workOrderName,
        };
        this.updateForm++;
      });
    },
    getOperatorLabel(form) {
      if (form.operatorType == "dept") {
        // 显示部门
        return form.executiveAgencyName || form.executiveAgency;
      }

      let operatorName = form.operatorName;

      // if (this.postManageDictObj.hasOwnProperty(form.operator)) {
      //   // 显示岗位
      //   operatorName = this.postManageDictObj[form.operator];
      // } else {
      //   // 显示工位
      //   operatorName = form.operatorName;
      // }

      return operatorName || "";
    },
    handleSubmit() {
      if (!this.row?.id) {
        return;
      }
      this.$refs.ruleForm.validate((flag) => {
        if (flag) {
          this.saveLoading = true;
          const param = {
            id: this.row.id,
            operateType: "audit",
            auditResult: this.examineFrom.result,
            auditOpinion: this.examineFrom.opinion,
            classStartTime: this.row.classStartTime,
            classEndTime: this.row.classEndTime,
            className: this.row.className,
            groupName: this.row.groupName,
          };
          saveTask(param)
            .then((res) => {
              if (res.code == 200) {
                this.msgSuccess("操作成功！");
                this.$emit("refresh");
                this.dialogVisible = false;
              }
            })
            .finally(() => {
              this.saveLoading = false;
            });
        }
      });
    },
    // 修改填报内容按钮操作
    handleModify() {
      this.modifyDialogVisible = true;
      this.key++;
    },
    // 打开修改填报内容弹框回调
    handleModifyOpen() {},
    // 关闭修改填报内容弹框回调
    handleModifyClose() {},
    // 提交表单
    handleSubmitModify() {
      const submitResult = this.$refs.ModifyFillForm.getSubmitData();
      if (!submitResult) {
        return;
      }

      const {
        taskContentDtoList,
        workOrderNo,
        groupId,
        groupName,
        className,
        classId,
      } = submitResult;

      const params = {
        missionCenterId: this.row.id,
        execStatus: "complete",
        execResult: null,
        workOrderNo,
        taskContentDtoList,
        classStartTime: this.row.classStartTime,
        classEndTime: this.row.classEndTime,
        className,
        classId,
        groupId,
        groupName,
      };
      this.$confirm("是否确认提交表单？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.toSubmitModify(params);
        })
        .catch(() => {});
    },
    // 提交修改填报内容
    toSubmitModify(params) {
      this.modifyLoading = true;
      saveTaskContent(params)
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("修改成功！");
            this.$emit("refresh");
            this.modifyDialogVisible = false;
            // 查询任务详情
            this.getTaskDetail();
            // 获取表单内容
            this.getFormContent();
          }
        })
        .finally(() => {
          this.modifyLoading = false;
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-row {
  margin-top: 10px;
  font-size: 15px;
  display: flex;
  align-items: center;
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.dialog-content {
  position: relative;
  .modify-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
